<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>系统登录</h2>
        <p>欢迎使用管理系统</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <!-- 验证码输入框 -->
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              size="large"
              prefix-icon="Shield"
              clearable
              class="captcha-input"
            />
            <div class="captcha-image-container" @click="refreshCaptcha">
              <img
                v-if="captchaImage"
                :src="captchaImage"
                alt="验证码"
                class="captcha-image"
                title="点击刷新验证码"
              />
              <div v-else class="captcha-loading">
                <i class="el-icon-loading"></i>
                加载中...
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe"> 记住密码 </el-checkbox>
          <el-link type="primary" class="forgot-password">忘记密码?</el-link>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            class="login-btn"
            @click="handleLogin"
          >
            {{ loading ? "登录中..." : "登录" }}
          </el-button>
        </el-form-item>

        <div class="register-link">
          您没有账号？ <el-link type="primary">注册</el-link>
        </div>
      </el-form>

      <!-- 测试账号提示 -->
      <div class="test-account">
        <p>测试账号：</p>
        <p>用户名：admin / user</p>
        <p>密码：123456</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { login, getCaptcha } from "@/api/user";
import type { LoginParams } from "@/api/user";  // 导入新的类型
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const router = useRouter();

// 表单引用
const loginFormRef = ref<FormInstance>();

// 加载状态
const loading = ref(false);

// 验证码相关
const captchaImage = ref<string>("");
const captchaKey = ref<string>("");

// 登录表单数据
const loginForm = reactive({
  username: "",
  password: "",
  captcha: "",
  rememberMe: false,
});

// 表单验证规则
const loginRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度为 2-20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度为 6-20 个字符", trigger: "blur" },
  ],
  captcha: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 6, message: "验证码长度为 4-6 个字符", trigger: "blur" },
  ],
};

// 模拟用户数据
const mockUsers = [
  { username: "admin", password: "123456", role: "admin" },
  { username: "user", password: "123456", role: "user" },
];

// 模拟登录API
const mockLogin = async (username: string, password: string) => {
  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 1000));

  const user = mockUsers.find(
    (u) => u.username === username && u.password === password
  );

  if (user) {
    return {
      code: 0,
      msg: "登录成功",
      data: {
        token: `mock_token_${Date.now()}`,
        userInfo: {
          id: 1,
          username: user.username,
          role: user.role,
          email: `${user.username}@example.com`,
        },
      },
    };
  } else {
    throw new Error("用户名或密码错误");
  }
};

// 获取验证码
const refreshCaptcha = async () => {
  // 首先设置一个测试验证码，确保界面能正常显示
  console.log("设置测试验证码");
  captchaKey.value = "test_key_" + Date.now();
  // 创建一个包含随机验证码的SVG图片
  const randomCode = Math.random().toString(36).substring(2, 6).toUpperCase();
  captchaImage.value = "data:image/svg+xml;base64," + btoa(`
    <svg width="120" height="40" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" style="stop-color:#f0f8ff;stop-opacity:1" />
          <stop offset="100%" style="stop-color:#e6f3ff;stop-opacity:1" />
        </linearGradient>
      </defs>
      <rect width="120" height="40" fill="url(#bg)" stroke="#409eff" stroke-width="1" rx="4"/>
      <text x="60" y="26" text-anchor="middle" fill="#409eff" font-family="Arial, sans-serif" font-size="18" font-weight="bold">${randomCode}</text>
      <line x1="10" y1="15" x2="110" y2="25" stroke="#409eff" stroke-width="1" opacity="0.3"/>
      <line x1="20" y1="30" x2="100" y2="10" stroke="#409eff" stroke-width="1" opacity="0.3"/>
    </svg>
  `);

  try {
    const response = await getCaptcha();
    console.log("完整验证码响应:", response);
    console.log("response.data:", response.data);

    // 处理不同可能的数据结构
    let captchaData = null;

    if (response.data) {
      // 尝试不同的数据结构路径
      if (response.data.data) {
        captchaData = response.data.data;
      } else if (response.data.captchaKey || response.data.captchaImage) {
        captchaData = response.data;
      } else {
        captchaData = response.data;
      }
    }

    console.log("解析的验证码数据:", captchaData);

    if (captchaData) {
      // 尝试获取captchaKey
      const apiCaptchaKey = captchaData.captchaKey || captchaData.key || captchaData.uuid || '';

      // 尝试获取captchaImage，可能是base64格式或URL
      let imageData = captchaData.captchaImage || captchaData.captchaBase64 || captchaData.image || captchaData.img || captchaData.base64 || '';

      // 如果是base64数据但没有前缀，添加前缀
      if (imageData && !imageData.startsWith('data:image/') && !imageData.startsWith('http')) {
        imageData = `data:image/png;base64,${imageData}`;
      }

      console.log("API返回的验证码Key:", apiCaptchaKey);
      console.log("API返回的验证码图片:", imageData ? "图片数据已获取" : "图片数据为空");

      // 如果API返回了有效数据，使用API数据，否则保持测试数据
      if (apiCaptchaKey && imageData) {
        captchaKey.value = apiCaptchaKey;
        captchaImage.value = imageData;
        console.log("使用API验证码数据");
      } else {
        console.log("API数据不完整，使用测试验证码");
      }
    } else {
      console.log("无法解析验证码数据，使用测试验证码");
    }
  } catch (error) {
    console.error("获取验证码失败:", error);
    console.log("保持使用测试验证码");
  }
};

// 处理登录 - 修改参数格式
const handleLogin = async () => {
  console.log("🚀 开始登录流程");
  console.log("📝 当前表单数据:", {
    username: loginForm.username,
    password: loginForm.password,
    captcha: loginForm.captcha,
    captchaKey: captchaKey.value
  });

  try {
    // 表单验证
    console.log("✅ 开始表单验证");
    await loginFormRef.value?.validate();
    console.log("✅ 表单验证通过");

    if (!captchaKey.value) {
      console.log("❌ 验证码Key为空");
      ElMessage.error("请先获取验证码");
      await refreshCaptcha();
      return;
    }

    console.log("🔑 验证码Key存在:", captchaKey.value);
    loading.value = true;

    // 🔥 关键修改：字段名改为后端期望的大小写格式
    const params: LoginParams = {
      UserName: loginForm.username,        // 改为 UserName (首字母大写)
      Password: loginForm.password,        // 改为 Password (首字母大写)
      CaptchaCode: loginForm.captcha,      // 改为 CaptchaCode (首字母大写)
      CaptchaKey: captchaKey.value         // 改为 CaptchaKey (首字母大写)
    };

    console.log("准备发送的登录参数:", params);
    console.log("JSON字符串化后的参数:", JSON.stringify(params));
    console.log("参数类型检查:", {
      UserName: typeof params.UserName,
      Password: typeof params.Password,
      CaptchaCode: typeof params.CaptchaCode,
      CaptchaKey: typeof params.CaptchaKey
    });

    // 检查必填字段
    if (!loginForm.username) {
      ElMessage.error("请输入用户名");
      return;
    }
    if (!loginForm.password) {
      ElMessage.error("请输入密码");
      return;
    }
    if (!loginForm.captcha) {
      ElMessage.error("请输入验证码");
      return;
    }

    const response = await login(params);
    console.log("login response:", response);
    console.log("🔍 登录响应详细分析:");
    console.log("  - response.data:", response.data);
    console.log("  - response.data.data:", response.data?.data);
    console.log("  - response.data.code:", response.data?.code);
    console.log("  - response.data.msg:", response.data?.msg);

    // 判断是否登录成功
    if (response.data && (response.data.code === 0 || response.data.code === 200)) {
      const responseData = response.data.data || response.data;
      console.log("✅ 登录成功，处理响应数据:");
      console.log("  - responseData:", responseData);
      console.log("  - responseData.token:", responseData.token);
      console.log("  - responseData.userInfo:", responseData.userInfo);

      // 尝试不同可能的token字段名
      const tokenValue = responseData.token || responseData.accessToken || responseData.access_token || responseData.Token;
      console.log("🔑 尝试获取token:", tokenValue);

      // 保存登录信息到本地存储
      if (tokenValue) {
        localStorage.setItem("token", tokenValue);
        console.log("✅ Token已保存:", tokenValue);
      } else {
        console.log("❌ 未找到token字段");
      }

      if (responseData.userInfo) {
        localStorage.setItem("userInfo", JSON.stringify(responseData.userInfo));
        console.log("✅ 用户信息已保存:", responseData.userInfo);
      } else {
        console.log("❌ 未找到userInfo字段");
      }

      // 验证token是否正确保存
      const savedToken = localStorage.getItem("token");
      console.log("🔍 验证保存的token:", savedToken);

      // 记住密码功能
      if (loginForm.rememberMe) {
        localStorage.setItem("rememberedUsername", loginForm.username);
        localStorage.setItem("rememberedPassword", loginForm.password);
      } else {
        localStorage.removeItem("rememberedUsername");
        localStorage.removeItem("rememberedPassword");
      }

      ElMessage.success("登录成功！");

      // 跳转到用户管理页面
      setTimeout(() => {
        router.replace("/home");
      }, 1000);
    } else {
      // 登录失败，刷新验证码
      const errorMsg = response.data?.msg || "登录失败";
      ElMessage.error(errorMsg);
      await refreshCaptcha();
      loginForm.captcha = "";
    }
  } catch (error: any) {
    console.error("登录失败:", error);
    ElMessage.error(error.message || "登录失败，请重试");
    // 登录失败时刷新验证码
    await refreshCaptcha();
    loginForm.captcha = "";
  } finally {
    loading.value = false;
  }
};

// 初始化记住的密码
const initRememberedInfo = () => {
  const rememberedUsername = localStorage.getItem("rememberedUsername");
  const rememberedPassword = localStorage.getItem("rememberedPassword");

  if (rememberedUsername && rememberedPassword) {
    loginForm.username = rememberedUsername;
    loginForm.password = rememberedPassword;
    loginForm.rememberMe = true;
  }
};

// 组件挂载时初始化
onMounted(() => {
  initRememberedInfo();
  refreshCaptcha(); // 页面加载时获取验证码
});
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.login-header {
  text-align: center;
  padding: 40px 20px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.login-header h2 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.login-form {
  padding: 30px;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 8px;
}

/* 验证码容器样式 */
.captcha-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image-container {
  width: 120px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  cursor: pointer;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  transition: all 0.3s;
}

.captcha-image-container:hover {
  border-color: #409eff;
  background: #ecf5ff;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-loading {
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 记住密码和忘记密码 */
.login-form :deep(.el-form-item:nth-child(4)) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.forgot-password {
  margin-left: auto;
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.login-btn:hover {
  opacity: 0.9;
}

/* 注册链接 */
.register-link {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin-top: 16px;
}

.test-account {
  text-align: center;
  padding: 0 30px 30px;
  color: #666;
  font-size: 12px;
  line-height: 1.5;
  background: #f8f9fa;
  border-top: 1px solid #eee;
}

.test-account p {
  margin: 4px 0;
}

.test-account p:first-child {
  color: #333;
  font-weight: 500;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    padding: 10px;
  }

  .login-box {
    max-width: 100%;
  }

  .login-header {
    padding: 30px 20px 15px;
  }

  .login-header h2 {
    font-size: 24px;
  }

  .login-form {
    padding: 20px;
  }

  .captcha-container {
    flex-direction: column;
    gap: 8px;
  }

  .captcha-image-container {
    width: 100%;
    height: 45px;
  }
}
</style>
